package com.example.origin.demo.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.function.Supplier;

/**
 * @author yutao.zhang2.o
 */
public class RequestCacheHolder {

    public static final String LOCAL_CACHE_ID = "REQUEST_CACHE_ID";

    //Singleton单例
    private RequestCacheHolder() {
    }


    @SuppressWarnings("unchecked")
    public static <T> T get(String key, Supplier<T> supplier) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        String name = String.join(":", LOCAL_CACHE_ID, key);
        Object attribute = requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
        if (attribute == null) {
            synchronized (RequestCacheHolder.class) {
                attribute = requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
                if (attribute == null) {
                    T value = supplier.get();
                    requestAttributes.setAttribute(name, value, RequestAttributes.SCOPE_REQUEST);
                    return value;
                }
            }
        }
        return (T) attribute;
    }
}
